/**
 * Project: complex.mina
 * 
 * File Created at 2011-3-16
 * $Id: Provider.java 129 2011-03-18 03:43:37Z ymkyve501@163.com $
 * 
 * Copyright 1999-2100 Alibaba.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.complex.mina;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * Provider服务提供者
 * 
 * @author gaoliang
 * @date 2011-3-16
 */
public class Provider {
    public static void main(String[] args) throws Exception {
        try{
            //启动自己的服务
            startProvider();
            
            //连接到server
            connect();
        }catch (Exception e){
            e.printStackTrace();
        }
       
    }
    
   
    private static void connect() {
        //连接到server,告诉server自己可以提供什么服务
        NioSocketConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new TextLineCodecFactory()));
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new ProviderHandler());

        //连接到服务器
        ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 12345));
        future.awaitUninterruptibly(3000);
        IoSession session = future.getSession();
        //写入数据
        //提供的服务名serviceName1,版本version1
        //地址localhost:23456
        session.write("Provider=serviceName1:version1//localhost:23456");
        
        //通知monitor
        Monitor.log("Provider");
    }

    //启一个服务,来处理client过来的请求
    private static void startProvider() throws Exception {
        NioSocketAcceptor acceptor = new NioSocketAcceptor();
        //filter chain
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
        //handler
        acceptor.setHandler(new ProviderHandler());
        //bind
        acceptor.bind(new InetSocketAddress(23456));

        System.out.println("provider start");
    }
}
